//
//  LoginViewController.m
//  HomeFinder
//
//  Created by zhenguanqing on 16/2/26.
//  Copyright © 2016年 蒋永昌. All rights reserved.
//

#import "LoginViewController.h"
#import "RegisterViewController.h"
#import "ForgetViewController.h"
#import "ImageVV.h"

#import <AVOSCloud/AVOSCloud.h>
#import <Masonry.h>
#import <AVOSCloudSNS.h>
#import <LeanCloudSocial/AVUser+SNS.h>


#define k_width self.view.bounds.size.width
#define k_height self.view.bounds.size.height

@interface LoginViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property(nonatomic,strong) ImageVV *iconView;
@property(nonatomic,strong) UITextField *userTF;
@property(nonatomic,strong) UITextField *passwordTF;
@property(nonatomic,strong) UIButton *forgetButton;
@property(nonatomic,strong) UIButton *loginButton;

@property(nonatomic,strong) UIButton *QQButton;
@property(nonatomic,strong) UIButton *wechatButton;
@property(nonatomic,strong) UIButton *weiboButton;
@property(nonatomic,assign) BOOL flag;


@end

@implementation LoginViewController

-(void)viewWillAppear:(BOOL)animated{

    self.tabBarController.tabBar.hidden = YES;
    


}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationItem.title = @"登录";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"Comment_Icon_Back"] style:UIBarButtonItemStylePlain target:self action:@selector(goBackAction:)];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@"注册" style:UIBarButtonItemStylePlain target:self action:@selector(registAction:)];
    
    [self addViews];

    
    
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSSinaWeibo withAppKey:@"1957741275" andAppSecret:@"f91736dc9221926045bb6e35d997160d" andRedirectURI:@"http://wanpaiapp.com/oauth/callback/sina"];
    
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSQQ withAppKey:@"1105046908" andAppSecret:@"RqrGGrsLXRjnwoUd" andRedirectURI:nil];
    
    
    [AVOSCloudSNS setupPlatform:AVOSCloudSNSWeiXin withAppKey:@"wxd930ea5d5a258f4f" andAppSecret:@"db426a9829e4b49a0dcac7b4162da6b6" andRedirectURI:nil];
    
}

-(void)addViews{

    //头像
    self.iconView = [[ImageVV alloc]initWithImage:[UIImage imageNamed:@"head"]];
    self.iconView.layer.masksToBounds = YES;
    self.iconView.layer.cornerRadius = k_width * 0.15;
    [self.view addSubview:self.iconView];
    self.iconView.userInteractionEnabled = YES;
    [self.iconView MyTarget:self Action:@selector(getPicture)];
    
    [self.iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(k_width * 0.3, k_width * 0.3));
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view.mas_top).offset(k_height * 0.24);
        
    }];
    
    
    //邮箱/手机号
    self.userTF = [[UITextField alloc]init];
    self.userTF.placeholder = @"手机号";
    self.userTF.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.userTF];
    
    [self.userTF mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.width.mas_equalTo(k_width * 0.8);
        make.height.mas_equalTo(k_height * 0.055);
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.view.mas_top).offset(k_height * 0.4);
        
    }];
    
    
    
    //密码
    self.passwordTF = [[UITextField alloc]init];
    self.passwordTF.placeholder = @"请输入密码";
    self.passwordTF.borderStyle = UITextBorderStyleRoundedRect;
    [self.view addSubview:self.passwordTF];
    
    [self.passwordTF mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.equalTo(self.userTF);
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.userTF.mas_centerY).offset(k_height * 0.1);
        
        
    }];
    
    //忘记密码
    self.forgetButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.forgetButton setTitle:@"忘记密码？" forState:UIControlStateNormal];
    [self.view addSubview:self.forgetButton];
    
    [self.forgetButton addTarget:self action:@selector(forgetAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.forgetButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.mas_equalTo(CGSizeMake(80, 20));
        make.right.equalTo(self.passwordTF.mas_right);
        make.top.equalTo(self.passwordTF.mas_bottom).offset(20);
        
        
    }];
    
    
    //登录按钮
    self.loginButton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [self.loginButton setTitle:@"登录" forState:UIControlStateNormal];
    self.loginButton.backgroundColor = [UIColor colorWithRed:0.373 green:0.551 blue:1.000 alpha:1.000];
    self.loginButton.tintColor = [UIColor whiteColor];
    [self.view addSubview:self.loginButton];
    [self.loginButton addTarget:self action:@selector(loginAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.loginButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.equalTo(self.userTF).multipliedBy(0.9);
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.passwordTF.mas_centerY).offset(k_height * 0.15);
        
    }];
    
    
    //qq登录
    self.QQButton = [[UIButton alloc]init];
    [self.QQButton setImage:[UIImage imageNamed:@"Share_QQ"] forState:UIControlStateNormal];
    [self.view addSubview:self.QQButton];
    
    [self.QQButton addTarget:self action:@selector(qqAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.QQButton mas_makeConstraints:^(MASConstraintMaker *make) {
       
        make.size.mas_equalTo(CGSizeMake(k_width* 0.13, k_width* 0.13));
        make.centerX.equalTo(self.view).offset(-k_width * 0.26);
        make.centerY.equalTo(self.loginButton.mas_bottom).offset(k_height * 0.1);
        
    }];

    
    //微信登录
    
    self.wechatButton = [[UIButton alloc]init];
    [self.wechatButton setImage:[UIImage imageNamed:@"Share_WeChat"] forState:UIControlStateNormal];
    [self.view addSubview:self.wechatButton];
    
    [self.wechatButton addTarget:self action:@selector(wechatAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.wechatButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.equalTo(self.QQButton);
        make.centerX.equalTo(self.view);
        make.centerY.equalTo(self.loginButton.mas_bottom).offset(k_height * 0.1);
        
    }];

    
    //微博登录
    
    self.weiboButton = [[UIButton alloc]init];
    [self.weiboButton setImage:[UIImage imageNamed:@"Share_Sina"] forState:UIControlStateNormal];
    [self.view addSubview:self.weiboButton];
    
    [self.weiboButton addTarget:self action:@selector(weiboAction) forControlEvents:UIControlEventTouchUpInside];
    
    [self.weiboButton mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.size.equalTo(self.QQButton);
        make.centerX.equalTo(self.view).offset(k_width * 0.26);
        make.centerY.equalTo(self.loginButton.mas_bottom).offset(k_height * 0.1);
        
    }];



}

// 点击选取图片
- (void)getPicture{
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc]init];
    
    imagePicker.delegate = self;
    imagePicker.allowsEditing = YES;
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"本地" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:imagePicker animated:YES completion:nil];
        
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    
    [alert addAction:action1];
    [alert addAction:action2];
    [alert addAction:action3];
    
    [self presentViewController:alert animated:YES completion:nil];
    

}


// 相册代理方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    
//    self.iconView.image = [UIImage imageNamed:@""];
    
    self.iconView.image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
//    [self.icon setImage:self.iconImage forState:UIControlStateNormal];
    
    [self dismissViewControllerAnimated:YES completion:^{
        

    }];
    
    self.flag = YES;
    
}


// 登陆按钮点击事件
- (void)loginAction{
    
    
    [AVUser logInWithUsernameInBackground:self.userTF.text password:self.passwordTF.text block:^(AVUser *user, NSError *error) {
        if (user != nil) {
            
            NSLog(@"登陆成功%@",user);
            
            if (self.flag == YES) {
                
                NSData *imageData = UIImageJPEGRepresentation(self.iconView.image, .2f);
                AVFile *imageFile = [AVFile fileWithData:imageData];
                [user setObject:imageFile forKey:@"Picture"];
                
                [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                    if (succeeded) {
                        
                        [self.navigationController popViewControllerAnimated:YES];
                        
                    }else{
                        NSLog(@"失败:%@" , error);
                    }
                }];
                
                self.flag = NO;

            }
            
            [self.navigationController popViewControllerAnimated:YES];

            
        } else {
            

            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"登陆失败" message:@"用户或密码不正确" preferredStyle:UIAlertControllerStyleAlert];
            UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                
            }];
            
            UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
            
            [alert addAction:action1];
            [alert addAction:action2];
            
            [self presentViewController:alert animated:YES completion:nil];
            


            
            
            NSLog(@"登陆失败:%@",error);
        }
    }];

}


-(void)goBackAction:(UIBarButtonItem*)sender{

    [self.navigationController popViewControllerAnimated:YES];

}

// 忘记密码跳转事件
-(void)forgetAction:(UIButton *)sender{


    ForgetViewController *forgetVC = [[ForgetViewController alloc]init];
    
    [self.navigationController pushViewController:forgetVC animated:YES];

}

// 注册用户跳转
-(void)registAction:(UIBarButtonItem*)sender{

    RegisterViewController *registerVC = [[RegisterViewController alloc]init];
    
    [self.navigationController pushViewController:registerVC animated:YES];

}

#pragma mark---------第三方登陆----------------

// qq第三方登陆
- (void)qqAction{
    
    [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
        if (error) {
            
            NSLog(@"%@",error);
        } else {
            NSString *accessToken = object[@"access_token"];
            NSString *username = object[@"username"];
            NSString *avatar = object[@"avatar"];
            //            NSDictionary *rawUser = object[@"raw-user"]; // 性别等第三方平台返回的用户信息
            NSString *sex = [object[@"raw-user"] objectForKey:@"gender"];
//            NSString *picture = object[@"attached"];
            
            //...
            AVFile *file =[AVFile fileWithURL:avatar];
//            [file getData];// 注意这一步很重要，这是把图片从原始地址拉去到本地
            NSLog(@"登陆成功,%@",object);
            NSLog(@"$$$$$$$$$$$$$$$$$%@",username);
            
            [AVUser loginWithAuthData:object platform:AVOSCloudSNSPlatformQQ block:^(AVUser *user, NSError *error) {
                if (error) {
                    // 登录失败，可能为网络问题或 authData 无效
                    NSLog(@"失败:%@",error);
                } else {
                    // 登录成功
                    
                    [[AVUser currentUser] setObject:avatar forKey:@"attached"];
                    [user setObject:[NSString stringWithFormat:@"%@" , sex] forKey:@"gender"];
                    [user setObject:file forKey:@"Picture"];
                    
                    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            
                            [self.navigationController popViewControllerAnimated:YES];
                            
                        }else{
                            NSLog(@"失败:%@" , error);
                        }
                    }];

                    
                    
                    
                }
            }];
            
        }
    } toPlatform:AVOSCloudSNSQQ];
}

// 微信第三方登陆
- (void)wechatAction{
    
    [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
        if (error) {
            
            NSLog(@"%@",error);
            
        } else {
            //            NSString *accessToken = object[@"access_token"];
            NSString *username = object[@"username"];
            NSString *avatar = object[@"avatar"];
            //            NSDictionary *rawUser = object[@"raw-user"]; // 性别等第三方平台返回的用户信息
            NSString *sex = [object[@"raw-user"] objectForKey:@"sex"];

            //...headimgurl
            AVFile *file =[AVFile fileWithURL:avatar];

            
            NSLog(@"登陆成功,%@",object);
            NSLog(@"$$$$$$$$$$$$$$$$$%@",username);
            
            [AVUser loginWithAuthData:object platform:AVOSCloudSNSPlatformWeiXin block:^(AVUser *user, NSError *error) {
                if (error) {
                    // 登录失败，可能为网络问题或 authData 无效
                    NSLog(@"失败:%@",error);
                } else {
                    // 登录成功
                    
                    [[AVUser currentUser] setObject:avatar forKey:@"attached"];
                    [user setObject:[NSString stringWithFormat:@"%@" , sex] forKey:@"gender"];

                    [user setObject:file forKey:@"Picture"];

                    
                    [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                        if (succeeded) {
                            
                            [self.navigationController popViewControllerAnimated:YES];
                            
                        }else{
                            NSLog(@"失败:%@" , error);
                        }
                    }];

                    
                    
                    
                }
            }];
            
            
            
        }
    } toPlatform:AVOSCloudSNSWeiXin];
    

}

// 微博第三方登陆
- (void)weiboAction{
    
    [AVOSCloudSNS loginWithCallback:^(id object, NSError *error) {
        if (error) {
        } else {
            
            
            
            
            //            NSString *accessToken = object[@"access_token"];
            NSString *username = object[@"username"];
            //            NSString *avatar = object[@"avatar"];
            
            NSLog(@"object === %@" , object);
            NSLog(@"username = %@" , username);
        }
    } toPlatform:AVOSCloudSNSSinaWeibo];

}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
